﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SlamCms.SharePoint.Migration
{
	public class MigratableQuickLaunchItem : IMigratable
	{
		public string Title { get; set; }
		public string Url { get; set; }
		public bool IsExternal { get; set; }
		public List<MigratableQuickLaunchItem> Children { get; set; }

		public MigratableQuickLaunchItem()
		{
			Children = new List<MigratableQuickLaunchItem>();
		}

		public XElement ToXml()
		{
			XElement node = new XElement("QuickLaunchItem");
			node.Add(new XAttribute("Title", Title));
			node.Add(new XAttribute("Url", Url));
			node.Add(new XAttribute("IsExternal", IsExternal));

			if (Children.Count > 0)
			{	
				node.Add(ChildrenToXml());
			}

			return node;
		}

		public void FromXml(XElement element)
		{
			this.Title = element.Attribute("Title").Value;
			this.Url = element.Attribute("Url").Value;
			this.IsExternal = bool.Parse(element.Attribute("IsExternal").Value);
			ChildrenFromXml(element);
		}

		private XElement ChildrenToXml()
		{
			XElement childrenNode = new XElement("Children");
			foreach (var child in Children)
			{
				childrenNode.Add(child.ToXml());
			}
			return childrenNode;
		}

		private void ChildrenFromXml(XElement element)
		{
			if (element.Element("Children") != null)
			{
				foreach (XElement childElement in element.Element("Children").Elements())
				{
					MigratableQuickLaunchItem childItem = new MigratableQuickLaunchItem();
					childItem.FromXml(childElement);
					Children.Add(childItem);
				}
			}
		}
	}
}
